package com.googlecode.monitoria.client;

 import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.Viewport;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.googlecode.monitoria.client.gui.FirstRunScreen;
import com.googlecode.monitoria.client.gui.HomeScreen;
import com.googlecode.monitoria.client.gui.LoginScreen;
import com.googlecode.monitoria.client.services.MonitoriaServiceAsync;
import com.googlecode.monitoria.client.to.UserTO;

/**
 * 
 * Entry point classes define <code>onModuleLoad()</code>.
 * 
 * @author Ricardo Araújo Santos - ricardo@lsd.ufcg.edu.br
 */
public class Application implements EntryPoint {
	
	private static Application singleton;

	/**
	 * Return the unique instance of this application.
	 * @return The unique instance of this application.
	 */
	public static Application get(){
		return singleton;
	}

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		singleton = this;
		checkFirstRun();
	}
	
	/**
	 * Check if this is the first time this application is being used. If so, it triggers the 
	 * administration account creation, otherwise it forwards to login screen.
	 */
	private void checkFirstRun(){
		MonitoriaServiceAsync.Util.getInstance().isFirstRun( new AsyncCallback<Boolean>() {
			
			public void onSuccess( Boolean result ) {
				if( result ){
					setFirstRunScreen();
				}else{
					setLoginScreen();
				}
			}
			public void onFailure( Throwable arg0 ) {
				
			}
		});
	}

	/**
	 * Puts a panel into the viewport.
	 * @param panel A new panel.
	 */
	private void addToViewport(LayoutContainer panel){
		RootPanel.get().clear();
		Viewport v = new Viewport();
		v.setLayout(new FitLayout());
		v.add(panel);
		RootPanel.get().add(v);
	}
	
	/**
	 * Shows log in screen when there's no logged user. Otherwise, it redirects do the home screen.
	 */
	public void setLoginScreen() {
		RootPanel.get().clear();
		MonitoriaServiceAsync.Util.getInstance().getLoggedUser( new AsyncCallback<UserTO>() {
			public void onFailure(Throwable arg0) {
				arg0.printStackTrace();
			}
			public void onSuccess(UserTO loggedUser) {
				if(loggedUser == null){
					addToViewport(new LoginScreen());
				}else{
					setHomeScreen(loggedUser);
				}
			}
		});
	}
	
	/**
	 * Shows the first usage screen to allow administration information set up.
	 */
	private void setFirstRunScreen() {
		addToViewport(new FirstRunScreen());
	}

	/**
	 * Shows home screen.
	 * @param loggedUser Logged user information.
	 */
	public void setHomeScreen(UserTO loggedUser){
		addToViewport(new HomeScreen(loggedUser));
	}
}
